<template>
  <n-card :bordered="false" class="proCard">
    <BasicForm :collapsed="false" @register="register" @reset="handleReset" @submit="handleSubmit">
      <template #anchorSelect="{ model, field }">
        <n-date-picker
          v-model:formatted-value="model[field]"
          clearable
          type="daterange"
          value-format="yyyy-MM-dd"
        />
      </template>
    </BasicForm>

    <BasicTable
      ref="actionRef"
      :actionColumn="actionColumn"
      :columns="columns"
      :request="loadDataTable"
      :row-key="(row) => row.id"
      :scroll-x="2048"
      @update:checked-row-keys="onCheckedRow"
    >
      <template #tableTitle>
        <span><b>汇总</b></span> <b>:</b>
        <span style="color: red; margin-left: 10px"
          ><b>{{ totalAmount }}</b>
        </span
        >
      </template>
  <template #toolbar>
    <n-button type="primary" @click="reloadTable">刷新数据</n-button>
  </template>
    </BasicTable>
  </n-card>
</template>

<script lang="ts" setup>
  import { h, onMounted, reactive, ref, unref } from 'vue';
  import { useDialog, useMessage } from 'naive-ui';
  import { BasicTable ,TableAction} from '@/components/Table';
  import { BasicForm, FormSchema, useForm } from '@/components/Form/index';
  import { columns } from './columns';
  import { getRechargeFlow ,itemRepay } from '@/api/player/rechargeFlow';
  import { formatToDate } from '@/utils/dateUtil';
  import { useUserStore } from '@/store/modules/user';

  const schemas: FormSchema[] = [
    {
      field: 'userId',
      labelMessage: '玩家ID',
      component: 'NInput',
      label: '玩家ID',
      componentProps: {
        placeholder: '玩家ID',
        // style: { width: '150px' },
        onInput: (e: any) => {
          console.log(e);
        },
      },
    },
    {
      field: 'roleId',
      component: 'NInput',
      label: '角色ID',
      componentProps: {
        placeholder: '角色ID',
        // style: { width: '200px' },
        onInput: (e: any) => {
          console.log(e);
        },
      },
    },
    {
      field: 'orderNo',
      component: 'NInput',
      label: 'CP订单号',
      componentProps: {
        placeholder: 'cp订单号',
        // style: { width: '300px' },
        onInput: (e: any) => {
          console.log(e);
        },
      },
    },
    {
      field: 'timeRange',
      label: '日期',
      componentProps: {
        placeholder: '日期',
        // style: { width: '300px' },
      },
      slot: 'anchorSelect',
    },
    {
      field: 'payWay',
      component: 'NSelect',
      label: '支付方式',
      componentProps: {
        placeholder: '支付方式',
        style: { width: '150px' },
        options: (function () {
          var arr = [
            {
              label: '微信',
              value: 'wechat',
            },
            {
              label: '支付宝',
              value: 'alipay',
            },
          ];
          return arr;
        })(),
        onInput: (e: any) => {
          console.log(e);
        },
      },
    },
    {
      field: 'payStatus',
      component: 'NSelect',
      label: '支付状态',
      defaultValue: 'success',
      componentProps: {
        placeholder: '支付状态',
        style: { width: '150px' },
        options: (function () {
          var arr = [
            {
              label: '已支付',
              value: 'success',
            },
            {
              label: '未支付',
              value: 'paying',
            },
          ];
          return arr;
        })(),
        onInput: (e: any) => {
          console.log(e);
        },
      },
    },
  ];

  const message = useMessage();
  const dialog = useDialog();
  const userStore = useUserStore();
  const actionRef = ref();

  const formParams = reactive({
    userId: 0,
    payStatus: 'success',
  });
  const isShowOpt = userStore.getRoleType == 'super'; //是否显示操作按钮
  

  const [register, {}] = useForm({
    gridProps: { cols: '1 s:1 m:2 l:3 xl:5 2xl:4' },
    labelWidth: 80,
    isFull: false,
    schemas,
  });

  const actionColumn = reactive({
    width: 80,
    title: '操作',
    key: 'action',
    fixed: 'right',
    render(record) {
      return h(TableAction as any, {
        style: 'button',
        actions: [
          {
            label: '补发',
            onClick: handRepay.bind(null, record),
            type: 'error',
            ifShow: () => {
              return isShowOpt;
            },
          },
        ],
        select: (key) => {
          message.info(`您点击了，${key} 按钮`);
        },
      });
    },
  });

  var totalAmount = 0;
  const loadDataTable = async (res) => {
    if (!formParams.userId) {
      formParams.userId = 0;
    } else {
      formParams.userId = parseInt(formParams.userId);
    }
    const param = { ...formParams, ...res };
    // console.log('param');
    // console.log(param);
    delete param.makeDate;
    const data = await getRechargeFlow(param);
    totalAmount = data.totalAmount;
    return data;
  };

  function onCheckedRow(rowKeys) {
    console.log(rowKeys);
  }

  function reloadTable() {
    actionRef.value.reload();
  }
  /**
   * 补发
   * @param record 
   */
  function handRepay(record: Recordable) {
    console.log('点击了补发：', record);
    dialog.info({
      title: '提示',
      content: `您确定补发 ${record.propsName} 吗？`,
      positiveText: '确定',
      negativeText: '取消',
      style:'color:red',
      onPositiveClick: async () => {
        await itemRepay({ 
            amount: record.amount,
            payExtra: record.payExtra,
            payStatus: record.payStatus,
            chanId: record.chanId,
            cpOrderNo: record.cpOrderNo,
            userId: record.userId,
          });
        message.success('补发成功');
        reloadTable();
      },
      onNegativeClick: () => {},
    });
  }

  function handleSubmit(values: Recordable) {
    console.log('submit', values);
    let tempParams = unref(formParams);
    tempParams = Object.assign(tempParams, values);
    if (values.makeDate) {
      let [startTime, endTime]: [number, number] = values.makeDate;
      let startTimeS = formatToDate(new Date(startTime));
      let endTimeS = formatToDate(new Date(endTime));
      tempParams = Object.assign(tempParams, { startTime: startTimeS, endTime: endTimeS });
    }
    reloadTable();
  }

  function handleReset(values: Recordable) {
    console.log(values);
  }

  onMounted(async () => {
   
  });
</script>

<style lang="less" scoped></style>
